package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"server/internal/app/model"
	"server/internal/app/serv"
	"server/internal/database"
	"server/internal/pkg/response"
	"strconv"
	"strings"
	"time"
)

// EnterpriseApi 企业管理
var EnterpriseApi = new(enterpriseApi)

type enterpriseApi struct {
	model.Enterprise
}

// List 列表
func (a enterpriseApi) List(c *gin.Context) {
	Db := database.DB         //初始化Db
	Db = Common.Query(Db, c)  //查询构造
	Db = Common.Paging(Db, c) //分页

	//快速搜索
	quickSearch := c.Query("quickSearch")
	if quickSearch != "" {
		Db = Db.Where("unit_name like ?", "%"+quickSearch+"%")
	}

	_, list, total := serv.Enterprise.Reads(Db)

	response.SuccessList(c, list, total)
}

// Detail 单条
func (a enterpriseApi) Detail(c *gin.Context) {
	id := c.Query("id")
	_, detail := serv.Enterprise.Read(id)

	response.SuccessData(c, detail, "")
}

// Add 添加
func (a enterpriseApi) Add(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "data": "1", "err": err.Error()})
		return
	}
	userInfo, _ := c.Get("userInfo")
	a.UserId = userInfo.(model.User).ID
	a.TissueId = userInfo.(model.User).TissueId
	if err := serv.Enterprise.Create(a.Enterprise); err.Error == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Fail(c, err.Error, "添加失败")
	}
}

// Edit 编辑
//func (a enterpriseApi) Edit(c *gin.Context) {
//
//	if err := c.ShouldBindJSON(&a); err != nil {
//		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "data": "1", "err": err.Error()})
//		return
//	}
//
//	if err := serv.Enterprise.Update(a.Enterprise); err.Error == nil {
//		response.Success(c, "", "编辑成功")
//	} else {
//		response.Fail(c, err.Error, "编辑失败")
//	}
//}

// Edit 编辑 （现在是PC端的申请修改）
func (a enterpriseApi) Edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "data": "1", "err": err.Error()})
		return
	}

	b := model.EnterpriseUpdate{}
	b.Enterprise = a.Enterprise
	b.EnterpriseId = a.ID
	b.ID = 0
	userInfo, _ := c.Get("userInfo")
	b.UserId = userInfo.(model.User).ID
	t := time.Now()
	b.CreateTime = int(t.Unix())
	b.UpdateTime = int(t.Unix())
	b.Status = 0
	if err := serv.EnterpriseUpdate.Update(b); err.Error == nil {
		response.Success(c, "", "提交成功等待管理员审核")
	} else {
		response.Fail(c, err.Error, "提交失败")
	}
}

// Del 删除
func (a enterpriseApi) Del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "参数错误", "data": "1", "err": err.Error()})
		return
	}

	if err := serv.Enterprise.Delete(param.Ids); err.Error == nil {
		response.Success(c, "", "删除成功")
	} else {
		response.Fail(c, err.Error, "删除失败")
	}
}

// Export 导出
func (a enterpriseApi) Export(c *gin.Context) {
	Db := database.DB        //初始化Db
	Db = Common.Query(Db, c) //查询构造
	//Db = Common.Paging(Db, c) //分页

	//快速搜索
	quickSearch := c.Query("quickSearch")
	if quickSearch != "" {
		Db = Db.Where("unit_name like ?", "%"+quickSearch+"%")
	}

	_, list, _ := serv.Enterprise.Reads(Db)
	data := [][]any{
		{"地区", "单位名称", "统一社会信用代码", "单位性质", "单位地址", "联系人", "联系电话", "职工数量", "是否建会", "上传时间", "修改时间", "状态"},
	}

	Db = database.DB
	isMember := map[int]string{0: "否", 1: "是"}
	status := map[int]string{0: "未审核", 1: "正常"}

	for _, v := range list {
		createTime := time.Unix(int64(v.CreateTime), 0).Format("2006-01-02 15:04:05")
		updateTime := time.Unix(int64(v.UpdateTime), 0).Format("2006-01-02 15:04:05")
		table := []any{v.City, v.UnitName, v.CreditCode, v.EnterpriseTypeName, v.UnitAddress, v.Contacts,
			v.ContactNumber, v.StaffNum, isMember[v.IsMember], createTime, updateTime, status[v.Status]}
		data = append(data, table)

	}
	xlsx, err := serv.Enterprise.GenerateXlsx(data, "导出订单信息")
	if err != nil {
		response.Fail(c, err.Error(), "失败")
		return
	} else {
		response.Success(c, xlsx, "成功")

	}

}

// 导入
func (a enterpriseApi) Import(c *gin.Context) {
	type Param struct {
		Path string `json:"path"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Fail(c, "", err.Error())
		return
	}
	if param.Path == "" {
		response.Fail(c, "", "文件路径为空")
		return
	}

	f, err := excelize.OpenFile(param.Path)
	if err != nil {
		response.Fail(c, "", err.Error())
		return
	}
	defer func() {
		if err = f.Close(); err != nil {
			response.Fail(c, "", err.Error())
			return
		}
	}()

	//获取 Sheet1 上所有单元格
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		fmt.Println(err)
		return
	}

	var enterpriseList []model.Enterprise
	Db := database.DB
	_, unitTypeList, _ := serv.EnterpriseType.Reads(Db)
	isMemberList := map[string]int{"是": 1, "否": 0}
	statusList := map[string]int{"正常": 1, "未审核": 0}

	userInfo, _ := c.Get("userInfo")
	t := time.Now()
	for k, row := range rows {
		if k < 1 {
			continue
		}
		companyInfo := model.Enterprise{}

		for _, unitType := range unitTypeList {
			if unitType.Name == row[3] {
				companyInfo.UnitType = unitType.ID
				break
			}

		}

		address := strings.Split(row[0], "-")
		areaName := ""
		for _, v := range address {
			areaName = v
		}

		//查询地址最后一级id  有就存
		area := model.Area{}
		Db.Model(&area).Where("name=?", areaName).First(&area)

		companyInfo.AreaId = area.ID
		companyInfo.City = row[0]
		companyInfo.UserId = userInfo.(model.User).ID
		companyInfo.TissueId = userInfo.(model.User).TissueId
		//companyInfo.Village = rowAddress[3]
		companyInfo.UnitName = row[1]
		companyInfo.CreditCode = row[2]
		companyInfo.UnitAddress = row[4]
		companyInfo.Contacts = row[5]
		companyInfo.ContactNumber = row[6]
		companyInfo.StaffNum, _ = strconv.Atoi(row[7])
		companyInfo.IsMember = isMemberList[row[8]]
		companyInfo.CreateTime = int(t.Unix())
		companyInfo.UpdateTime = int(t.Unix())
		companyInfo.Status = statusList[row[11]]
		enterpriseList = append(enterpriseList, companyInfo)
		//number, _ := strconv.Atoi(row[21])
	}

	res := Db.Model(&enterpriseList).Create(&enterpriseList)

	response.Success(c, "", "导入成功："+strconv.Itoa(int(res.RowsAffected))+"条")
}
